package com.my.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 权限检查AOP
 * @author zzl
 */
@Aspect
@Order(1) //Order(1) 数值越小，表示aop的优先级越高
@Component
public class AuthAspect {

    /**
     * 对注解进行切入<br/>
     * 即标记了此注解的位置会被此类切入
     */
    @Pointcut("@annotation(com.my.aop.CheckAuth)")
    public void cut() {
    }

    /**
     * 在方法执行前校验，当前用户是否有执行权限
     */
    @Before("cut()")
    public void checkAuthBefore(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Object target = point.getTarget();
        try {
            Method method = target.getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
            CheckAuth auth = method.getAnnotation(CheckAuth.class);
            String role = (String) point.getArgs()[0];//此处假设访问的用户权限，实际业务中可以从会话中获取
            if (auth.value().equalsIgnoreCase(role)) {
                System.out.println("====>AuthAspect, 当前方法访问权限为：" + auth.value());
            } else {
                throw new RuntimeException("AuthAspect, 当前没有访问权限");
            }
        } catch (NoSuchMethodException ignore) {
        }

    }

}
